<template>
  <BasicDrawer v-bind="$attrs" :width="drawerWidth" :title="title" :show-footer="true" @register="registerInnerDrawer"
    @ok="handleSubmit" @close="resetForm">
    <BasicForm @register="registerForm">
      <!-- 社交账号 -->
      <template #contactSocialAccount>
        <Row v-for="(item, index) in contactSocialAccount" :key="item.id" :gutter="16" class="mb-8px">
          <Col :span="7">
          <Select v-model:value="item.type" placeholder="请选择账号类型" :key="index">
            <SelectOption v-for="item in ACCOUNT_TYPE" :key="item.value" :value="item.value">
              {{ item.label }}
            </SelectOption>
          </Select>
          </Col>
          <Col :span="14">
          <Input v-model:value="item.account" placeholder="请输入社交账号" :key="index" />
          </Col>
          <Col :span="3">
          <div class="flex" style="height: 100%">
            <Space>
              <MinusCircleOutlined v-if="contactSocialAccount.length !== 1" @click="removeSocialAccount(index)"
                class="cursor-pointer" :style="{ fontSize: '16px', color: '#c00017' }" />
              <PlusCircleOutlined v-if="index === contactSocialAccount.length - 1" @click="addSocialAccount"
                class="cursor-pointer" :style="{ fontSize: '16px', color: '#03a012' }" />
            </Space>
          </div>
          </Col>
        </Row>
      </template>
    </BasicForm>
  </BasicDrawer>
</template>

<script setup lang="ts">
import { BasicDrawer, useDrawerInner } from '@/components/Drawer';
import { BasicForm, useForm } from '@/components/Form';
import { computed, ref, unref, watch } from 'vue';
import { addCustomerContact, updateCustomerContact } from '@/api/customer';
import { addVendorContact, updateVendorContact } from '@/api/vendor';
import { drawerSchemas } from './contact.data';
import { useMaxWidthOrDefault } from '@/hooks/web/useSize';
import { Row, Col, Select, Input, Space } from 'ant-design-vue';
import { MinusCircleOutlined, PlusCircleOutlined } from '@ant-design/icons-vue';
import { getDictOptions } from '@/utils/dict';
import { DictEnum } from '@/enums/dictEnum';
defineOptions({ name: 'ContactDrawer' });

const emit = defineEmits(['register', 'reload']);
const SelectOption = Select.Option;
const ACCOUNT_TYPE = getDictOptions(DictEnum.ACCOUNT_TYPE);
const isUpdate = ref<boolean>(false);
const recordType = ref<string>('');
const drawerWidth = useMaxWidthOrDefault(700);
const title = computed<string>(() => {
  return isUpdate.value ? '编辑联系人' : '新增联系人';
});

const [registerInnerDrawer, { drawerLoading, closeDrawer }] = useDrawerInner(
  async (data: { record?: Recordable; update: boolean; recordId: string, type: string }) => {
    drawerLoading(true);
    const { record, update, recordId, type } = data;
    isUpdate.value = update;
    recordType.value = type;
    if (record) {
      setFieldsValue(type == 'customer' ? {
        ...record,
        customerId: recordId,
      } : {
        ...record,
        vendorId: recordId
      });
      if (record.contactSocialAccount) {
        contactSocialAccount.value = JSON.parse(record.contactSocialAccount);
      }
    } else {
      setFieldsValue(type == 'customer' ? {
        customerId: recordId,
      } : {
        vendorId: recordId
      });
      contactSocialAccount.value = [
        {
          id: Date.now(),
          type: '3',
          account: '',
        },
      ];
    }
    drawerLoading(false);
  },
);
const contactSocialAccount = ref([
  {
    id: Date.now(),
    type: '3',
    account: '',
  },
]);
function addSocialAccount() {
  contactSocialAccount.value.push({
    id: Date.now(),
    type: '3',
    account: '',
  });
}
function removeSocialAccount(index: number) {
  contactSocialAccount.value.splice(index, 1);
}
const [registerForm, { setFieldsValue, resetForm, validate }] = useForm({
  // layout: 'vertical',
  labelWidth: 100,
  name: 'address-drawer',
  showActionButtonGroup: false,
  baseColProps: { span: 24 },
  schemas: drawerSchemas,
});

async function handleSubmit() {
  try {
    drawerLoading(true);
    const data = await validate();
    if (unref(isUpdate)) {

      recordType.value == 'customer' ? await updateCustomerContact({
        ...data,
        contactIsMain: data.contactIsMain ? 1 : 0,
      }) : await updateVendorContact({
        ...data,
        contactIsMain: data.contactIsMain ? 1 : 0,
      });
    } else {
      recordType.value == 'customer' ? await addCustomerContact({
        ...data,
        contactIsMain: data.contactIsMain ? 1 : 0,
      }) : await addVendorContact({
        ...data,
        contactIsMain: data.contactIsMain ? 1 : 0,
      });;
    }
    emit('reload');
    closeDrawer();
    await resetForm();
  } catch (e) {
    console.log('e', e);
  } finally {
    drawerLoading(false);
  }
}
watch(
  () => contactSocialAccount.value,
  (v) => {
    setFieldsValue({
      contactSocialAccount: JSON.stringify(v),
    });
  },
  {
    deep: true,
  },
);
</script>
